package com.test.fileupload;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 上传文件，调用其它服务实现文件上传
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {
        MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
        String url = "http://localhost:9000/upload";
        file.transferTo(new File("f://docker.txt"));
        FileSystemResource ins = new FileSystemResource("f://docker.txt");
        map.add("file",ins);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        HttpEntity<MultiValueMap<String,Object>> httpEntity = new HttpEntity<>(map,headers);
        ResponseEntity<String> result = restTemplate.postForEntity(url, httpEntity, String.class);
        return "ok!" + result;
    }
}
